package com.oitsm.collection;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import com.oitsm.dispatcher.TaskService;
import com.oitsm.dispatcher.task.CollectTasker;
import com.oitsm.mo.cache.MonitorCache;
import com.oitsm.mo.entity.Monitor;
import com.oitsm.mo.entity.Schedule;
import com.oitsm.plugin.entity.Context;
import com.oitsm.plugin.entity.PluginMeta;
import com.oitsm.plugin.interfaces.Plugin;
import com.oitsm.plugin.service.PluginMetaService;

/**
 * 采集计划表 - 
 * @author Arab Runner
 * Jul 24, 2011 2:52:28 PM
 */
public class CollectionSchedule {
	private static ScheduledExecutorService scheduleScaner = null;
//	private static int maxQueuedTime = 60000;
	public static void init(){
		scheduleScaner = Executors.newSingleThreadScheduledExecutor();
		scheduleScaner.scheduleWithFixedDelay(new Runnable(){
			public void run() {
				for(Monitor m : MonitorCache.getAllMonitor()){
					if(isCollectable(m)){
						try{
							// 获取 plugin meta 和 plugin
							PluginMeta meta = PluginMetaService.getPluginMeta(m.getType());
							Plugin p = (Plugin) Class.forName(meta.getExcutor()).newInstance();
							
							// 创建上下文对象
							Context ctx = new Context(m.getProps());
							CollectTasker t = new CollectTasker(meta,p,ctx);
							
							// 设置回调
							t.addCallback(new MonitorCallback(m));
							
							// 添加到任务中,设置添加到队列的时间
							TaskService.addTask(t);
							m.setQueuedTime(System.currentTimeMillis());
						}catch(Exception e){
							e.printStackTrace();
						}
					}
				}
			}
		}, 0, 200, TimeUnit.MILLISECONDS);
	}
	
	private static boolean isCollectable(Monitor m){
		boolean c = false;
		Schedule s = m.getSchedule();
		// 没有放入队列中,并且当前时间>改采集的时间
		if(m.getQueuedTime() == -1 && s.getNextTime()!=null && System.currentTimeMillis()>=s.getNextTime()){
			c = true;
		}
		return c;
	}
}
